@inject ConfirmModalService ModalService
@using AliasVault.RazorComponents.Services
@implements IDisposable

@if (ModalService.IsVisible)
{
    <div class="fixed inset-0 z-[1000] bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center">
        <div class="relative p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3 text-center">
                <h3 class="text-lg leading-6 font-medium text-gray-900">@ModalService.Title</h3>
                <div class="mt-2 px-7 py-3">
                    <p class="text-sm text-gray-500">
                        @ConvertNewlinesToHtml(ModalService.Message)
                    </p>
                </div>
                <div class="items-center px-4 py-3">
                    <button id="confirmButton" class="px-4 py-2 bg-primary-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-300" @onclick="() => ModalService.CloseModal(true)">
                        @ModalService.ConfirmButtonText
                    </button>
                    <button id="cancelButton" class="mt-3 px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300" @onclick="() => ModalService.CloseModal(false)">
                        @ModalService.CancelButtonText
                    </button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    /// <inheritdoc/>
    protected override void OnInitialized()
    {
        ModalService.OnChange += StateHasChanged;
    }

    /// <inheritdoc/>
    public void Dispose()
    {
        ModalService.OnChange -= StateHasChanged;
    }

    /// <summary>
    /// Converts newline characters to HTML line breaks.
    /// </summary>
    /// <param name="text">The input text.</param>
    /// <returns>The text with newlines replaced by <br /> tags.</returns>
    private static MarkupString ConvertNewlinesToHtml(string text)
    {
        return (MarkupString)text.Replace(Environment.NewLine, "<br />").Replace("\n", "<br />");
    }
}
